import {combineReducers} from 'redux-immutable';
import * as actions from './actions';
import Immutable from 'immutable';
import {
    GET_CURRENT_USER_PAGE_PERMISSIONS_BEGIN,
    GET_CURRENT_USER_PAGE_PERMISSIONS_SUCCESS,
    GET_CURRENT_USER_PAGE_PERMISSIONS_FAIL
} from 'Shared/actions/currentUserContext';
import {DEFAULT_QUERY_OPTION} from './constants';

const list = (state, action) => {
    switch(action.type) {
        case actions.GET_LIST_DATA_BEGIN:
            return state.merge({
                isFetching: true,
                hasError: '',
            });
        case actions.GET_LIST_DATA_SUCCESS:
            return state.merge({
                isFetching: false,
                total: action.data.totalElements,
                hasError: '',
                data: action.data.content
            });
        case actions.GET_LIST_DATA_FAIL:
            return state.merge({
                isFetching: false,
                total: 0,
                data: [],
                hasError: action.message,
            });
        default:
            return state;
    }
};

const queryCondition = (state, action) => {
    switch(action.type) {
        case actions.SAVE_QUERY_CONDITION:
            return state.set(action.name, action.value);
        case actions.RESET_QUERY_PANEL:
            return Immutable.fromJS(DEFAULT_QUERY_OPTION);
        case actions.GET_LIST_DATA_SUCCESS:
            return state.withMutations(map =>
                map
                    .set('pageSize', action.condition.pageSize)
                    .set('sortField', action.condition.sortField)
                    .set('isDesc', action.condition.isDesc)
            );

        default:
            return state;
    }
};

const queryBySort = (state, action) => {
    switch(action.type) {
        case actions.GET_LIST_DATA_SUCCESS:
            return state.merge(action.condition);

        default:
            return state;
    }
};

export const permission = (state, action) => {
    switch(action.type) {
        case GET_CURRENT_USER_PAGE_PERMISSIONS_BEGIN:
            return state.merge(Immutable.fromJS({
                isFetching: true,
                message: ''
            }));
        case GET_CURRENT_USER_PAGE_PERMISSIONS_SUCCESS:
            return state.merge(Immutable.fromJS({
                isFetching: false,
                message: '',
                data: action.data
            }));
        case GET_CURRENT_USER_PAGE_PERMISSIONS_FAIL:
            return state.merge(Immutable.fromJS({
                isFetching: false,
                message: action.message
            }));
        default:
            return state;
    }
};

const appState = combineReducers({
    queryCondition,
    queryBySort,
});

const domainData = combineReducers({
    permission,
    list,
});

export default combineReducers({
    domainData,
    appState,
});
